package register

import (
	"fmt"
	"github.com/valyala/fasthttp"
	"log"
	"strings"
	"time"
)

type ForwardHandler struct {
	client   *Client
	toPeerId string
}

func (f *ForwardHandler) Handle(message []byte) {
	f.client.server.lock.Lock()
	peer, ok := f.client.server.clients[strings.ToLower(f.toPeerId)]
	f.client.server.lock.Unlock()
	log.Printf("[info] forward candidate:%v", peer.conn)
	if ok && peer.conn != nil {
		err := peer.sendMessage(message)
		if err != nil {
			log.Printf("[error] 500500500500500500500500500500500500500500:%s", err)
		}
		//f.client.server.lock.Unlock()
	} else {
		//f.client.server.lock.Unlock()
		go func() {
			log.Println("forward to station")
			const baseUrl = "push?to=%s"
			fastClient := &fasthttp.Client{
			//ReadTimeout: 5*time.Second,
			}
			req := fasthttp.AcquireRequest()
			req.Header.SetMethod("POST")
			req.SetRequestURI(fmt.Sprintf(baseUrl, f.toPeerId))
			req.SetHost(f.client.server.remoteHost)
			req.SetBody(message)
			resp := fasthttp.AcquireResponse()
			if err := fastClient.DoTimeout(req, resp, 10*time.Second); err != nil {
				log.Printf("[err]:forwardhandler forward message to transform server->%v", err)
			}
			//		TODO
		}()

	}
}

//node preority
//isp ----  nat -- region

//00:1c:42:0b:de:24
